// pages/start/start.js

var wxNetwork = require("../../utils/network.js");
var wxURL = require("../../utils/requestURL.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.isLogin();
    }, 5000)
  },

  isLogin(){

    var that = this;

    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) {

          var params = {'jsCode': res.code};
          var header = {'X-Requested-With':'XMLHttpRequest'};
          wxNetwork.postRequest(wxURL.post_usersAuth_URL, params, header, function (dict){     
            //本地保存：token作为用户标识
            wx.setStorageSync('token', dict.content.token);
            that.direct();
          },
            function (dict){

          },
            function (dict){

          })
        }
      },
      fail: function () {
        console.log("启用wx.login函数，失败！");
      }
    })
  },

  /** 判断每次进入的页面 */
  direct:function(){

    var isFir = wx.getStorageSync('isFirst');

    if (isFir == true)  //首次使用
    {
      var header = { 'Access-Token': wx.getStorageSync('token')};
      wxNetwork.getRequest(wxURL.get_queryUsers_URL, {}, header, function (dict)       {
        var waterUsers = dict.content.waterUsers;

         if (waterUsers.length == 0) { //不存在用水户，显示认证页
           wx.navigateTo({
             url: '../userIdent/userIdent',
           })
         }
         else {  //存在用水户，到主页
           wx.switchTab({
             url: '../home/home',
           })
         }
      },
        function (dict) {

        },
        function (dict) {

        })
    }
    else {  //到欢迎页
      wx.redirectTo({
        url: "../../pages/welcome/welcome"
      })
    }
  }

})